package com.lakeworks.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

@Component
public class BarcodeGenerator {

    private static RedisTemplate<String,Long> barcodeRedisTemplate;

    private final Integer BARCODELENGTH = 12;

    @Autowired
    public BarcodeGenerator(RedisTemplate<String,Long> barcodeRedisTemplate) {
        this.barcodeRedisTemplate = barcodeRedisTemplate;
    }


    public String generator(String key) {
        StringBuffer builder = new StringBuffer(key);
        if(StringUtils.isNotBlank(key)){
           if(key.length() < BARCODELENGTH){
               ValueOperations<String,Long> ops = barcodeRedisTemplate.opsForValue();
               Long aLong = ops.increment(key, 1);
               int number = BARCODELENGTH - key.length();
               String paddedString = String.format("%0"+number+"d", aLong);
               StringBuffer code = builder.append(paddedString);
               return code.append(eanCode(code)).toString();
           }
        }
        return null;
    }

    //生成ean13校验码
    public int eanCode(StringBuffer code) {
        int c1 = 0;
        int c2 = 0;
        int sum = 0;
        int check;
        for (int i = 0; i < 12; i += 2) {
            c1 += (code.charAt(i) - '0');
            c2 += (code.charAt(i + 1) - '0');
        }
        sum = c1 + c2 * 3;
        check = (10 - sum % 10) % 10;
        return check;
    }

}





